<?php
// +----------------------------------------------------------------------
// | Author: derek <693472824@qq.com> <http://www.bloveambition.com/>
// +----------------------------------------------------------------------

namespace Api\Controller;
use Think\Model;
use Api\Logic\UserLogic;

/**
 * 预约服务控制器
 * @author derek <693472824@qq.com>
 */
class OrdersController extends BaseController {
    
    /**
     * 预约服务
     * @author derek <693472824@qq.com>
     */
    public function appointment(){
        
        $detailID = I('detail_id');
        $classID = I('class_id');
        $addressID = I('address_id');
        $data = I();
        
        $userID = $this->checkLogin('Orders/appointment', $data);
        
        if(empty($detailID) || empty($classID)){
            $this->error('请先选择服务类型', U('Class/viewAction'));
            exit();
        }
        
        $map['user_id'] = $userID;
        $userModel = M('User')->where($map)->find();
        
        //用户指定维修地址
        if(!empty($addressID)){
            $map['address_id'] = $addressID;
        }
        $addressModel = M('UserAddress')->where($map)->order('default_address,address_id')->find();
        
        //指定小哥
        if(!empty($data['worker_id']) && !empty($data['appointment'])){
            $worker = M('Worker')->where(array('worker_id'=>$data['worker_id']))->field('worker_id,account,name,site_id')->find();
        }
        $dateList = D('Worker', 'Logic')->schedule($data['worker_id'], $data['appointment']);
        
        //计算超范围服务费，用于提醒用户
        $orderLogic = D('Orders', 'Logic');
        $site = $orderLogic->getSite($addressModel, $worker['site_id']);
        $chargePrice = $orderLogic->getChargePrice($site);
        
        //用户已上传维修部位照片
        $recordStr = $data['record_id'];
        if(!empty($recordStr) && strpos($recordStr, ',')){
            $recordMap['record_id'] = array('in', $recordStr);
            $recordMap['order_id'] = '0';
            $recordList = M('OrdersRecord')->where($recordMap)->getField('record_id,fullpath,media_id');
        }
        
        //根据所选服务类型获取推荐小哥
        $workerMap = array();
        $classMap['class_id'] = $classID;
        $professionStr = M('Class')->where(array('class_id'=>$classID))->getField('profession');
        $profession = empty($professionStr) ? '' : explode(',', $professionStr);
        //$profession = is_array($profession) && count($profession) > 0 ? $profession[0] : '';
        
        if(!empty($site)){
            $workerMap['site_id'] = $site['site_id'];
        } 
        if(!empty($profession)){
            
            $professionSQL = '';
            foreach ($profession as $key=>$val){
                $professionSQL .= empty($professionSQL) ? '' : ' OR ';
                $professionSQL .= ' find_in_set('.$val.',profession) ';
            }
            
            $workerMap['_string'] = $professionSQL;
        }
        
        $workerView = D('WorkerView');
        $workerList = $workerView->where($workerMap)->getField('worker_id,name,eid,fullpath');
        //$tp = $workerView->getLastSql();
        //是否允许紧急服务
        $detailModel = M('ClassDetail')->where(array('detail_id'=>$detailID))->find();
        
        $this->assign('detail_id', $detailID);
        $this->assign('class_id', $classID);
        $this->assign('userModel', $userModel);
        $this->assign('addressModel', $addressModel);
        $this->assign('workerModel', $worker);
        $this->assign('appointment', $data['appointment']);
        $this->assign('emergency', $data['emergency']);
        $this->assign('delay', $data['delay']);
        $this->assign('dateList', $dateList);
        $this->assign('site_id', $site['site_id']);
        $this->assign('chargePrice', $chargePrice);
        $this->assign('record_id', $data['record_id']);
        $this->assign('recordList', $recordList);
        $this->assign('workerList', $workerList);
        $this->assign('detailModel', $detailModel);
        $this->assign('domain', 'http://'.$_SERVER['HTTP_HOST']);
        $this->display();
    }

    /**
     * ajax 下载微信服务器图片到本地，并返回本地图片路径
     */
    public function ajaxDownLoad(){
    
        $mediaID = I('media_id');
    
        if(empty($mediaID)){
    
            $this->result['msg'] = '参数异常';
            $this->ajaxReturn($this->result);
        }
    
        $orderLogic = D('Orders', 'Logic');
        $result = $orderLogic->ajaxDownLoad($mediaID, 'OrdersRecord');
    
        if($result && $result['fullpath']){
    
            $this->result['status'] = '1';
            $this->result['fullpath'] = $result['fullpath'];
            $this->result['record_id'] = $result['record_id'];
        }
    
        $this->ajaxReturn($this->result);
    }
    
    /**
     * 下单
     * 若指定小哥，则订单状态为 2，且发送推送消息能小哥
     */
    public function order(){
        
        $param = I();
        $userID = $this->checkLogin('Orders/order', $param);
        
        if(empty($param['address_id']) || empty($param['detail_id'])){
            $this->error('参数错误', 'Index/index');
        }
        
        $workerModel = M('Worker');
        
        $suffix = \Org\Util\String::randString(4, 1);
        $orderNo = substr($userID, 0, 1).substr(date('Ymd'), 2).$suffix;
        
        $data['user_id'] = $userID;
        $data['address_id'] = $param['address_id'];
        $data['order_no'] = $orderNo;
        $data['detail_id'] = $param['detail_id'];
        
        //紧急服务
        if($param['emergency'] == '2'){
            $data['emergency'] = '2';
            
            if(empty($param['delay'])){
                $this->error('参数错误', 'Index/index');
            }else{
                $data['delay'] = $param['delay'];
                $data['appointment'] = '0';
            }
            
        }else if($param['emergency'] == '1'){
            $data['emergency'] = '1';
            
            if(empty($param['appointment'])){
                $this->error('参数错误', 'Index/index');
            }else{
                $data['appointment'] = $param['appointment'];
                $data['delay'] = '0';
            }
        }
        
        //用户指定小哥
        if($param['worker_id']){
            $data['order_type'] = '2';
            $data['worker_id'] = $param['worker_id'];
            $data['status'] = '8';
        }else{
            $data['status'] = '1';
        }
        
        if(empty($param['site_id'])){
            $address = M('UserAddress')->where(array('address_id'=>$data['address_id']))->find();
            
            if(!empty($data['worker_id'])){
                $workerSiteID = $workerModel->where(array('worker_id'=>$data['worker_id']))->getField('site_id');
            }else{
                $workerSiteID = '';
            }
            
            $site = D('Orders', 'Logic')->getSite($address, $workerSiteID);
            $data['site_id'] = $site['site_id'];
        }else{
            $data['site_id'] = $param['site_id'];
        }
        
        $data['create_time'] = NOW_TIME;
        $data['remark'] = $param['remark'];
        
        $order = D('Orders');
        if($order->create($data)){
            $orderID = $order->add();
        }
        
        if($orderID){
            $recordStr = $param['record_id'];
            
            if(!empty($recordStr)){
                $recordStr = trim($recordStr, ',');
                $recordMap['record_id'] = array('in', $recordStr);
                $recordMap['create_time'] = array('gt', NOW_TIME-3600);     //一小时内上传的图片
                M('OrdersRecord')->where($recordMap)->setField('order_id', $orderID);
            }
            
            $messageModel = M('Message');
            
            if($data['status'] == '8'){
                
                $workerMap['worker_id'] = $data['worker_id'];
                
                $account = $workerModel->where($workerMap)->getField('account', true);
                
                $msgData['worker_id'] = $data['worker_id'];
                $msgData['msg_type'] = '8';
            }else{
                
                $workerMap['site_id'] = $data['site_id'];
                if($data['emergency'] == '2'){
                    $workerMap['member_type'] = '1';
                    $account = $workerModel->where($workerMap)->getField('account', true);
                    
                    if(empty($account)){
                        $workerMap['member_type'] = '2';
                        
                        $account = $workerModel->where($workerMap)->getField('account', true);
                        
                        $msgWorkerID = '2';
                    }
                }else{
                    $account = $workerModel->where($workerMap)->getField('account', true);
                }
                
                $msgData['worker_id'] = $data['emergency'] == '1' ? '0' : (empty($msgWorkerID) ? '1' : '2');          //非紧急订单推送给所有小哥，紧急订单只推送给自有小哥
                $msgData['msg_type'] = '4';
            }
            
            $msgData['site_id'] = $data['site_id'];
            $msgData['order_id'] = $orderID;
            $msgData['create_time'] = NOW_TIME;
            $msgData['sender'] = $userID;
            $msgData['receipt'] = $msgData['msg_type'] == '8' ? '2' : '1';
            
            $msgID = $messageModel->add($msgData);
            
            $extra['msg_type'] = $msgData['msg_type'];
            $extra['content'] = '';
            $extra['order_id'] = $orderID;
            $extra['order_no'] = $orderNo;
            $extra['emergency'] = $data['emergency'];
            $extra['appointment'] = $data['appointment'];
            $extra['delay'] = $data['delay'];
            
            api('Util/jPush', array($account, array(), $extra));
        }
        
        $this->redirect('Orders/result', 'order_id='.$orderID);
    }
    
    /**
     * 下单结果页面
     */
    public function result(){
        
        $orderID = I('order_id');
        $userID = $this->checkLogin('Orders/result', 'order_id='.$orderID);
        
        $map['order_id'] = $orderID;
        $map['user_id'] = $userID;
        $order = M('Orders')->where($map)->find();
        
        if($order){
            $result = '1';
        }else{
            $result = '2';
        }
        
        $this->assign('result', $result);
        $this->display();
    }
    
    /**
     * 用户订单
     */
    public function index(){
        
        $type = I('type');
        $type = !in_array($type, array('1', '2', '3', '4')) ? '1' : $type;
        
        $userID = $this->checkLogin('Orders/index', array('type'=>$type));
        
        $this->assign('type', $type);
        $this->display();
    }
    
    /**
     * 订单列表
     */
    public function ajax_orderList(){
        
        $start = I('lastIndex');
        $start = empty($start) || !is_numeric($start) ? '0' : $start;
        
        $userID = UserLogic::is_login();
        
        if(empty($userID)){
            
            $this->result['status'] = '-201';
        }else{
            
            //1.等待中（用户已下单，但无小哥接单 status=1/8）；2.服务中（小哥已接单直到服务结束 status=2/3/10）；
            //3.待支付（小哥服务已结束，等待用户支付 status=4/5）；4.历史订单（订单已结束或已取消，status=6/7）
            $type = I('tabIndex');
            $type = !in_array($type, array('1', '2', '3', '4')) ? '1' : $type;
            $map = array();
            $map['user_id'] = $userID;
            
            if($type == '1'){
                $map['status'] = array('in', '1,8');
            }elseif($type == '2'){
                $map['status'] = array('in', '2,3,10');
            }elseif ($type == '3'){
                $map['status'] = array('in', '4,5');
            }elseif ($type == '4'){
                $map['status'] = array('in', '6,7,9');
            }else{
                $map['status'] = '0';
            }
            
            $orderModel = D('OrdersDetailView');
            
            $total = $orderModel->where($map)->count();
            
            if($start <= $total){
                
                $list = $orderModel->where($map)->order('create_time DESC')->limit($start, $this->limit)
                                ->getField('order_id,order_no,detail_name,emergency,appointment,delay,status,create_time');
            
                if(!empty($list)){
                    
                    $list = array_values($list);
                    $this->result['info'] = $list;
                }
            }
            
            $this->result['status'] = '1';
            
            if($start + $this->limit >= $total){
                $this->result['is_last'] = '1';
            }
        }
        
        $this->ajaxReturn($this->result);
    }
    
    /**
     * 订单详情
     */
    public function viewDetail(){
        
        $orderID = I('order_id');
        
        if(empty($orderID) || !is_numeric($orderID)){
            
            $this->error('参数错误', U('Orders/index'));
        }
        
        $map['order_id'] = $orderID;
        $orderModel = D('OrdersView');
        $order = $orderModel->where($map)->find();
        
        $recordList = M('OrdersRecord')->where(array('order_id'=>$orderID))->getField('savename, fullpath');
        
        if(!empty($order['worker_id'])){
            
            $worker = D('WorkerView')->where(array('worker_id'=>$order['worker_id']))
                        ->field('worker_id,account,name,eid,job,profession,sex,score,orders_sum,avg_hour,member_type,work_year,description,fullpath')
                        ->find();
            $this->assign('workerModel', $worker);
        }
        
        $this->assign('orderModel', $order);
        $this->assign('list', $recordList);
        $this->display();
    }

    /**
     * 用户取消订单
     */
    public function cancel(){
        
        $orderID = I('order_id');
        $userID = UserLogic::is_login();
        
        if(empty($orderID)){
            $this->result['status'] = '0';
        }else if(empty($userID)){
            $this->result['status'] = '-201';
        }else{
            
            $map['order_id'] = $orderID;
            $map['user_id'] = $userID;
            $data['reason'] = I('reason');
            $data['status'] = '7';
            
            M('Orders')->where($map)->save($data);
            $this->result['status'] = '1';
        }
        
        $this->ajaxReturn($this->result);
    }
    
    /**
     * 获取维修部位图片
     */
    public function ajax_recordList(){
        
        $recordStr = I('rstr');
        
        if(empty($recordStr)){
            $this->result['status'] = '0';
        }else{
        
            $recordList = explode(',', $recordStr);
            $map['record_id'] = array('in', $recordList);
            
            $rList = M('OrdersRecord')->where($map)->getField('record_id,name,fullpath,media_id');
            
            if(!empty($rList)){
                $this->result['status'] = '1';
                $this->result['info'] = $rList;
            }
        }
        
        $this->ajaxReturn($this->result);
    }
}
